// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,Radio, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import $ from 'jquery'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './newsBulletinAddStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import moment from 'moment';
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

const FormItem = Form.Item
const { RangePicker } = DatePicker

function timestampToTime() {
  var date = new Date();//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
  var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
    return Y+M+D+h+m+s;
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const newsBulletinAddView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let { temp,areaCheckAll,areaShow,userList,showUser,projectCheckAll,showProject,areaList,products,userCheckAll,query, actionType, btnLoading } = modelObj
  query.createTime = timestampToTime()
  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };
  const formItemLayout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 20 },
  };
 
  //区域改变时
  function inputAreaChange() {
    dispatch({
      type: `${namespace}/filterProjectList`,
      payload: {}
    })
  }

  //输入框改变时
  function inputChange (value, name) {
    let obj = {[name]: value}
    query = Object.assign(query, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  }

  function onCheckAllChange(e,type){
    if(type == 'areaCheckAll'){
      areaCheckAll = e.target.checked
      temp.areaIdList = e.target.checked&&areaList.length?areaList.map((item)=>{
        return item.value
      }):[]
      let list = []
      list = e.target.checked&&areaList.length?areaList.map((item)=>{
        return item.label
      }):[]
      query.areaName = list.length?list.join(','):''
      query.areaIds = temp.areaIdList.length?temp.areaIdList.join(','):''
      inputAreaChange()
    }else if(type == 'projectCheckAll'){
      projectCheckAll = e.target.checked
      temp.projectIdList = e.target.checked&&products.length?products.map((item)=>{
        return item.value
      }):[]
      let list1 = []
      list1 = e.target.checked&&products.length?products.map((item)=>{
        return item.label
      }):[]
      query.projectName = list1.length?list1.join(','):''
      query.projectIds = temp.projectIdList.length?temp.projectIdList.join(','):''

    }else if(type == 'userCheckAll'){
      userCheckAll = e.target.checked
      temp.userIdList = e.target.checked&&userList.length?userList.map((item)=>{
        return item.userId
      }):[]
      let list2 = []
      list2 = e.target.checked&&userList.length?userList.map((item)=>{
        return item.userName
      }):[]
      query.userName = list2.length?list2.join(','):''
      query.memberDatas = e.target.checked&&userList.length?userList:''
    }else{
      return
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {userCheckAll,query,projectCheckAll,areaCheckAll}
    })
  }

  function checkboxChange(checkedValues,type) {
   if(type == 'area'){
    temp.areaIdList = checkedValues
      let arr = []
      for(var item of areaList){
        for(var itemed of checkedValues){
          if(item.value == itemed){
            arr.push(item.label)
          }
        }
      }
      query.areaIds = checkedValues.length?checkedValues.join(','):''
      query.areaName = arr.length?arr.join(','):''
      areaCheckAll = checkedValues.length === areaList.length
      inputAreaChange()
    } else if(type == 'project'){
      temp.projectIdList = checkedValues
        let arr1 = []
        for(var item of products){
          for(var itemed of checkedValues){
            if(item.value == itemed){
              arr1.push(item.label)
            }
          }
        }
        query.projectIds = checkedValues.length?checkedValues.join(','):''
        query.projectName = arr1.length?arr1.join(','):''
        projectCheckAll = checkedValues.length === products.length
    }else if(type == 'user'){
      temp.userIdList = checkedValues
      let arr2 = []
      let arr3 = []
      for(var item of userList){
        for(var itemed of checkedValues){
          if(item.userId == itemed){
            arr2.push(item.userName)
            arr3.push(item)
          }
        }
      }
      query.memberDatas = arr3
      query.userName = arr2.length?arr2.join(','):''
      userCheckAll = checkedValues.length === userList.length

    }else{
      return
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query,userCheckAll,projectCheckAll,areaCheckAll}
    })
    
  }
  function onCheckboxClick(e){
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
  }
  function onCheckboxChange(e){
  }
  function showUserFun(e,type){
    e.stopPropagation();
    showUser = type
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {showUser}
    })
    if(actionType == 'check') return
    dispatch({
      type: `${namespace}/getUserList`,
      payload: {}
    })
  }
  function showProjectFun(e,type){
    e.stopPropagation();
    showProject = type
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {showProject}
    })
  }
  function showAreaFun(e,type){
    e.stopPropagation();
    areaShow = type
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {areaShow}
    })
  }
  function showFun(e){
    areaShow = false
    showProject = false
    showUser = false
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {areaShow,showProject,showUser}
    })
  }
  function submit(){
    dispatch({
      type: `${namespace}/editContent`,
      payload: {}
    })
  }
  function goback(){
    hashHistory.push({
      pathname: '/home/expandManage/newsBulletin',
      query: {}
    });
  }
  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button style={{display:actionType == 'check'?'none':'inline-block'}} type='primary' onClick={e => submit()} loading={btnLoading}>提交</Button>
        <Popconfirm placement="top" title={"是否确认关闭，确认后关闭页面，不保存数据。"} onConfirm={() => goback()} okText="确定" cancelText="取消">
          <Button>关闭</Button>
        </Popconfirm>
      </div>

      <CollapsiblePanels title="消息公告" hideUpDownBtn={true} >
        <div style={{minHeight: '640px'}} onClick={(e) => { showFun(e) }}>
        <Row>
          <Col span={8} style={{position: 'relative'}}>
            <FormItem label='所属区域'  {...formItemLayoutPro}>
              {getFieldDecorator('areaName', {
                rules: [{
                  required: true, whitespace: true, message: '请选择所属区域'
                }],
                initialValue: query.areaName
              })(
              //   <Select placeholder='请选择所属区域' onChange={(e) => { inputAreaChange(e, 'areaIds') }}>
              //   {areaList.map((item)=>{
              //       return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
              //     })}
              // </Select>
              <Input readOnly  placeholder='请选择所属区域' onClick={(e) => { showAreaFun(e,true) }} onChange={(e) => { inputChange(e.target.value, 'areaName') }} />
              )}
            </FormItem>
            <div  className={cx('tanchuang')} style={{display:areaShow?'block':'none', position: 'absolute',width: '100%',zIndex: 999,top: '38px'}}>
            <Col span={6}></Col>
            <Col span={14} style={{background: '#fff',border: '1px solid #e5e5e5',padding: '8px',overflowY: 'scroll',height: '222px'}}>
                <Checkbox style={{display:actionType == 'check'?'none':'inline-block',marginBottom: '12px'}} disabled={actionType == 'check'}
                    onChange={(e) =>{onCheckAllChange(e,'areaCheckAll')}}
                    onClick={(e) =>{onCheckboxClick(e)}}
                    checked={areaCheckAll}
                  >
                  全选
                </Checkbox>
                <span style={{display:actionType == 'check'?'none':'inline-block',color: '#1b88e2',cursor: 'pointer',position: 'absolute',right: '12px'}} onClick={(e) => { showAreaFun(e,false) }}>关闭</span>
                <Checkbox.Group disabled={actionType == 'check'} style={{ width: '100%' }}  value={temp.areaIdList} onChange={(e) =>{checkboxChange(e,'area')}}>
                { areaList == undefined ?null:areaList.map((item,key)=>{
                return <Row key={key}>
                        <Col span={24} className={cx('col_margin_bottom')}>
                            <div className={cx('flex')} style={{marginBottom: '12px'}}>
                              <Checkbox value={item.value} onClick={(e) =>{onCheckboxClick(e)}} onChange={(e) =>{onCheckboxChange(e,'area')}}>{item.label}</Checkbox>
                            </div> 
                          </Col>
                        </Row>
                  })}
                </Checkbox.Group>
              </Col>
            </div>   
          </Col>
        </Row>
        <Row>
          <Col span={8} style={{position: 'relative'}}>
            <FormItem label='所属项目'  {...formItemLayoutPro}>
              {getFieldDecorator('projectName', {
                rules: [{
                  required: true, whitespace: true, message: '请选择所属项目'
                }],
                initialValue: query.projectName
              })(
                <Input readOnly   placeholder='请选择项目' onClick={(e) => { showProjectFun(e,true) }} onChange={(e) => { inputChange(e.target.value, 'projectName') }} />
              )}
            </FormItem>
            <div className={cx('tanchuang')} style={{display:showProject?'block':'none', position: 'absolute',width: '100%',zIndex: 999,top: '38px'}}>
            <Col span={6}></Col>
            <Col span={14} style={{background: '#fff',border: '1px solid #e5e5e5',padding: '8px',overflowY: 'scroll',height: '222px'}}>
                <Checkbox style={{display:actionType == 'check'?'none':'inline-block',marginBottom: '12px'}} disabled={actionType == 'check'}
                    onChange={(e) =>{onCheckAllChange(e,'projectCheckAll')}}
                    onClick={(e) =>{onCheckboxClick(e)}}
                    checked={projectCheckAll}
                  >
                  全选
                </Checkbox>
                <span style={{display:actionType == 'check'?'none':'inline-block',color: '#1b88e2',cursor: 'pointer',position: 'absolute',right: '12px'}} onClick={(e) => { showProjectFun(e,false) }}>关闭</span>
                <Checkbox.Group disabled={actionType == 'check'} style={{ width: '100%' }}  value={temp.projectIdList} onChange={(e) =>{checkboxChange(e,'project')}}>
                { products == undefined ?null:products.map((item,key)=>{
                return <Row key={key}>
                        <Col span={24} className={cx('col_margin_bottom')}>
                            <div className={cx('flex')} style={{marginBottom: '12px'}}>
                              <Checkbox value={item.value} onClick={(e) =>{onCheckboxClick(e)}} onChange={(e) =>{onCheckboxChange(e,'project')}}>{item.label}</Checkbox>
                            </div> 
                          </Col>
                        </Row>
                  })}
                </Checkbox.Group>
              </Col>
            </div>
          </Col>
        </Row>
        <Row>
          <Col span={8} style={{position: 'relative'}}>
            <FormItem label='选择人员'  {...formItemLayoutPro}>
              {getFieldDecorator('userName', {
                rules: [{
                  required: true, whitespace: true, message: '请选择人员'
                }],
                initialValue: query.userName
              })(
                <Input readOnly  placeholder='请选择人员' onClick={(e) => { showUserFun(e,true) }} onChange={(e) => { inputChange(e.target.value, 'userName') }} />
              )}
            </FormItem>
            <div className={cx('tanchuang')} style={{display:showUser?'block':'none', position: 'absolute',width: '100%',zIndex: 999,top: '38px'}}>
            <Col span={6}></Col>
            <Col span={14} style={{background: '#fff',border: '1px solid #e5e5e5',padding: '8px',overflowY: 'scroll',height: '222px'}}>
                <Checkbox style={{display:actionType == 'check'?'none':'inline-block',marginBottom: '12px'}} disabled={actionType == 'check'}
                    onChange={(e) =>{onCheckAllChange(e,'userCheckAll')}}
                    onClick={(e) =>{onCheckboxClick(e)}}
                    checked={userCheckAll}
                  >
                  全选
                </Checkbox>
                <span style={{display:actionType == 'check'?'none':'inline-block',color: '#1b88e2',cursor: 'pointer',position: 'absolute',right: '12px'}}  onClick={(e) => { showUserFun(e,false) }}>关闭</span>
                <Checkbox.Group disabled={actionType == 'check'} style={{ width: '100%' }}  value={temp.userIdList} onChange={(e) =>{checkboxChange(e,'user')}}>
                { userList == undefined ?null:userList.map((item,key)=>{
                return <Row key={key}>
                        <Col span={24} className={cx('col_margin_bottom')}>
                            <div className={cx('flex')} style={{marginBottom: '12px'}}>
                              <Checkbox style={{display:actionType == 'check'?'none':'block'}} value={item.userId} onClick={(e) =>{onCheckboxClick(e)}} onChange={(e) =>{onCheckboxChange(e,'user')}}>{item.userName}</Checkbox>
                              <span style={{display:actionType == 'check'?'block':'none'}}>{item.userName}</span>
                            </div> 
                          </Col>
                        </Row>
                  })}
                </Checkbox.Group>
              </Col>
            </div>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem label='公告标题'  {...formItemLayout}>
              {getFieldDecorator('title', {
                rules: [{
                  required: true, whitespace: true, message: '请输入公告标题'
                }],
                initialValue: query.title
              })(
                <Input disabled={actionType == 'check'} placeholder='请输入公告标题' onChange={(e) => { inputChange(e.target.value, 'title') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem label='内容描述'  {...formItemLayout}>
              {getFieldDecorator('msg', {
                rules: [{
                  required: true, whitespace: true, message: '请输入内容描述'
                }],
                initialValue: query.msg
              })(
                <Input disabled={actionType == 'check'} placeholder='请输入内容描述' onChange={(e) => { inputChange(e.target.value, 'msg') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem
                  {...formItemLayoutPro}
                  label="创建时间"
                  >
                  {getFieldDecorator('createTime', {
                    rules:[{required:true,message:'请选择创建时间'},],
                    initialValue: query.createTime ? moment(query.createTime, 'YYYY-MM-DD HH:mm:ss') : null
                  })(
                    <DatePicker disabled={true} format="YYYY-MM-DD HH:mm:ss" onChange={(e, val) => inputChange(val, 'createTime')}  />
                  )}
              </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label='创建人'  {...formItemLayoutPro}>
              {getFieldDecorator('creater', {
                rules: [{
                  required: true, whitespace: true, message: '请输入创建人'
                }],
                initialValue: query.creater
              })(
                <Input disabled={true} placeholder='请输入创建人' onChange={(e) => { inputChange(e.target.value, 'creater') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        </div>       
      </CollapsiblePanels>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(newsBulletinAddView))